<template>
  <div id="app">
    <el-dialog :visible.sync="submitDialog" title="订单出库" center top="10px" width="60%">
      <div class="top">
        <div style="display: flex;justify-content: center;margin-top: 15px">
          <span>门店名称：{{ info.assignName }}</span>
          <span>项目负责人：{{ info.placeName }}</span>
          <span>联系电话：{{ info.placePhone }}</span>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 10px">
          <span>门店地址：{{ info.address }}</span>
          <span style="color: red">发货仓库：{{ info.areaName }}</span>
          <span>备注：{{ info.remark }}</span>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 10px">
          <span>材料总价：{{ info.totalPrice }}</span>
          <span>折扣金额：0</span>
          <span>应收金额：{{ info.totalPrice }}</span>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 10px">
          <span>回款金额：<el-input size="small" v-model="receiveConut" style="width: 200px"></el-input></span>
          <span style="display: flex">回款凭证：<div v-for="(v,i) in preSalesImg"><el-image :key="i"
                                                                                       style="width: 50px; height: 50px"
                                                                                       ref="preview" :src="'https://'+v"
                                                                                       :preview-src-list="preSalesImgList">
        </el-image>
           <div @click="deletePic(i)">
          <el-icon name="delete"></el-icon>
        </div>
          </div></span>
          <span>回款日期：<el-date-picker
              v-model="receiveDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              size="small"
              placeholder="选择日期">
    </el-date-picker></span>
        </div>
      </div>
      <div class="table" style="margin-top: 10px">
        <el-table :data="materialData" max-height="500px"
                  border stripe :cell-style="{ 'textAlign': 'center' }"
                  :header-cell-style="{ 'background-color': '#303e9d', 'color': 'white', 'textAlign': 'center' }">
          <el-table-column prop="name" label="分类名称" width="200px">
          </el-table-column>
          <el-table-column label="选择材料">
            <template slot-scope="scope">
              <el-tag type="danger" style='width: 100%;'
                      v-if="!scope.row.list">当前材料,暂无库存
              </el-tag>
              <el-select v-else size="small" clearable v-model="scope.row.materials"
                         placeholder="请选择材料" style="width: 100%">
                <el-option v-for="(item,index) in scope.row.list" :key="item.materialId"
                           :label="`名称:${item.materialName} - 编码:${item.materialId} - 库存:${item.inventoryNum} - 价格:${item.salePrice} -  色号:${item.color}`"
                           :value="index">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="buyCount" label="数量" width="120px"></el-table-column>
        </el-table>
      </div>
      <span slot="footer">
         <el-button style="background-color:#e0e0e0;" @click="submitDialog=false">取消</el-button>
         <el-button style="color: #FFFFFF;" @click="submit">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "submitOrder",
  data() {
    return {
      submitDialog: false,
      info: {},
      materialData: [],
      receiveConut: "",
      receiveDate: "",
      preSalesImg: [],
      preSalesImgList: [],
      list: {
        item: []
      }
    }
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
  },
  methods: {
    handleOpen(val) {
      this.info = val
      this.receiveDate = ""
      this.receiveConut = ""
      this.preSalesImg = []
      this.submitDialog = true
      this.$api.wechatGetClassificationList({wechatOrderId: val.wechatOrderId, areaId: val.areaId}).then(res => {
        // console.log(res)
        res.map(el => {
          // el.materials = el.list ? el.list[0] : ''
          el.materials = el.list ? 0 : ''
        })
        this.materialData = res
      })
    },
    deletePic(i) {
      this.preSalesImg.splice(i, 1)
    },
    handlePaste(event) {
      if (!this.submitDialog) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/img/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': window.$quinn.getStorage("tokenv3")
        }
      })
          .then(response => {
            this.preSalesImg.push(response.data.result[0]);
            this.preSalesImgList.push('https://' + response.data.result[0]);
          })
          .catch(error => {
          });
    },
    submit() {
      if (!this.preSalesImg.toString()) return this.$message.warning("请上传回款凭证！")
      // const materialsArray = this.materialData.filter(item => item.materials).map(item => ({
      //   ...item.materials,
      //   outNum: item.buyCount,
      // }));

      const materialsArray = this.materialData.map((item, index) => {
        // console.log(item.list[item.materials])
        return {
          ...item.list[item.materials || 0],
          outNum: item.buyCount,
        }
      })
      const data = {
        orderNo: this.info.orderNo,
        refundAmount: this.receiveConut,
        refundProof: this.preSalesImg,
        refundTime: this.receiveDate,
        list: materialsArray
      }
      this.$api.wechatOutMaterialDelivery(data).then(res => {
        if (res > 0) {
          this.$message.success("操作成功！")
          this.submitDialog = false
          this.$emit('addStatus', 1);
        }
      })
    }
  },

}
</script>

<style scoped lang="less">
.top {
  span {
    display: block;
    width: 33%;
  }
}
</style>